package com.justnow.offer;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author justnow
 * Created on 2020-09-20
 * Description
 *
 *
 * 3
 * 3 3
 * ###
 * #@*
 * ***
 * 3 4
 * ####
 * #@.*
 * **.*
 * 3 3
 * .#.
 * #@#
 * .#.
 */
public class Duxiaoman02 {

    public static int min = Integer.MAX_VALUE;
    public static boolean flag = false;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int T = scanner.nextInt();
        for (int i = 0; i < T; i++) {
            int N = scanner.nextInt();
            int M = scanner.nextInt();
            scanner.nextLine();
            char[][] array = new char[N][M];
            for (int r = 0; r < N; r++) {
                String lines = scanner.nextLine();
                char[] temp = lines.toCharArray();
                array[r] = temp;
            }

            for (int r = 0; r < N; r++) {
                boolean loopflag = false;
                for (int c = 0; c < M; c++) {
                    if ('@' == array[r][c]) {
                        loopflag = true;
                        List<Character> path = new ArrayList<>();
                        dfs(array, r, c, path, min, flag);
                        if (min == 0) {
                            System.out.println(0);
                        } else {
                            if (!flag) {
                                System.out.println(-1);
                            } else {
                                System.out.println(min);
                            }
                            break;
                        }

                    }
                }
                if (loopflag)
                    break;
                ;

            }
        }

    }

    private static void dfs(char[][] array, int r, int c, List<Character> path, int min, boolean flag) {

        if (r == 0 || c == 0 || r == array.length - 1 || c == array[0].length - 1) {
            flag = true;
            int count = 0;
            for (Character character : path) {
                if (character == '.') {
                    count++;
                }
            }
            min = Math.min(count, min);
            return;
        }
        if (r >= 0 && c >= 0 && r < array.length || c < array[0].length && '#' == array[r][c]) {
            return;
        }
        path.add(array[r][c]);
        char temp = array[r][c];
        array[r][c] = '#';
        dfs(array, r + 1, c, path, min, flag);
        dfs(array, r - 1, c, path, min, flag);
        dfs(array, r, c + 1, path, min, flag);
        dfs(array, r, c - 1, path, min, flag);
        array[r][c] = temp;
        path.remove(array[r][c]);
    }
}
